import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class UDPServer {
    private static final int PORT = 9090;
    private static final String BACKUP_FILE_PATH = "message_backup.txt"; // 设置备份文件路径

    public static void main(String[] args) {
        try {
            startUdpServer();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void startUdpServer() {
        DatagramSocket socket = null;
        try {
            // 创建DatagramSocket对象，监听端口9090
            socket = new DatagramSocket(PORT);
            System.out.println("UDP服务器已启动，等待接收消息...");

            // 创建备份文件（如果文件不存在则创建）
            File backupFile = new File(BACKUP_FILE_PATH);
            if (!backupFile.exists()) {
                backupFile.createNewFile();
            }

            while (true) {
                // 接收数据包
                byte[] buffer = new byte[1024];
                DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

                // 接收数据
                socket.receive(packet);
                String message = new String(packet.getData(), 0, packet.getLength());

                // 获取客户端的IP地址并打印消息
                System.out.println("\n----------------------------");
                System.out.println("接收到来自 " + packet.getAddress().getHostAddress() + " 的消息: ");
                System.out.println(message);
                System.out.println("----------------------------");

                // 备份数据到文件
                backupMessage(message);

                // 可选：接收到某个特定消息后退出服务器
                if ("exit".equalsIgnoreCase(message)) {
                    System.out.println("收到退出命令，服务器停止...");
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (socket != null && !socket.isClosed()) {
                socket.close();
                System.out.println("服务器已关闭");
            }
        }
    }

    /**
     * 备份接收到的消息到文件
     * @param message 接收到的消息
     */
    private static void backupMessage(String message) {
        // 获取当前时间作为消息的时间戳
        String timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());

        // 写入消息到备份文件
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(BACKUP_FILE_PATH, true))) {
            writer.write("[" + timestamp + "] " + message);
            writer.newLine(); // 添加新行
            System.out.println("消息已备份到文件");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
